<script lang="ts" setup>
import { ref } from 'vue'
import { showDialog } from 'vant';

const emits = defineEmits(['onConfirm'])
const inputEl = ref<HTMLInputElement | null>()
const canvalEl = ref<HTMLCanvasElement | null>()
let blobUri = ''
function onChange(e) {
  const file = e.target.files[0];
  console.log('file', file)
  
  compressImage(file, (uri) => {
    const size = getBase64ImageSize(uri)
    console.log('压缩后的大小:' + size+ 'kb')
    if (size > 1024 * 2) {
    showDialog({
      title: '提示',
      message: '您当前的图片过大，请选择其他图片或者使用拍照功能'
    })
    return
  }
    emits('onConfirm', uri)
    URL.revokeObjectURL(blobUri)
  })
}
function getBase64ImageSize(base64) {
  let str = atob(base64.split(',')[1]);
  let bytes = str.length;
  return bytes / 1024;
}
function compressImage(file, cb) {
  const imageUrl = URL.createObjectURL(file)
  blobUri = imageUrl
  const image = new Image()
  image.src = imageUrl
  const canvas = canvalEl.value!
  const ctx = canvas.getContext('2d')
  image.onload = () => {
    canvas.width = image.width
    canvas.height = image.height
    ctx?.drawImage(image, 0, 0, image.width, image.height)
    const uri = canvas.toDataURL('image/jpeg', 0.5)
    cb(uri)
  }
}
defineExpose({
  open: () => {
    inputEl.value?.click();
  }
})
</script>
<template>
  <input type="file" ref="inputEl" @change="onChange" style="display: none;" accept="image/*">
  <canvas ref="canvalEl" style="display: none;"></canvas>
</template>
<style lang="scss" scoped></style>